package org.skatiger.jrove.spring.tags.component;

import org.skatiger.jrove.ViewContext;
import org.skatiger.jrove.spring.tags.SpringComponent;
import org.springframework.validation.Errors;

public class BindErrors extends SpringComponent {
    public static final String ERRORS_VARIABLE_NAME = "errors";

    private String name;
    private Object previousObject;
    private Errors errors;

    protected String var;

    public String getVar() {
        return getPropertyValue("var", var, ERRORS_VARIABLE_NAME);
    }

    public void setVar(String var) {
        this.var = var;
    }

    /**
     * Set the name of the bean that this tag should check.
     */
    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return getPropertyValue("name", name);
    }

    public void capturePreivousValue(ViewContext context) {
        String var = getVar();
        Object obj = context.getAttribute(var);
        if (obj != null) {
            this.previousObject = obj;
            context.removeAttribute(var);
        }
    }

    public void restorePreivousValue(ViewContext context) {
        String var = getVar();
        if (previousObject != null) {
            context.setAttribute(var, this.previousObject);
        }
    }

    public Errors getErrors() {
        if (errors == null) {
            String resolvedName = getName();
            this.errors = getRequestContext().getErrors(resolvedName,
                    isHtmlEscape());
        }
        return this.errors;
    }

    @Override
    public boolean isRendered() {
        boolean rendered = super.isRendered();
        if (rendered) {
            rendered = getErrors() == null ? false : getErrors().hasErrors();
        }
        return rendered;
    }
}
